import "@assets/scss/app.scss";
import '@scripts/index';
import { $ } from '@utils/functions';
import { Wave } from "@scripts/wave";

function render(context: CanvasRenderingContext2D) {
  context.beginPath();
  context.arc(100, 100, 50, 0, Math.PI * 2, true);
  context.closePath();
  context.fillStyle = 'rgb(255,255,255)';
  context.fill();
}

function valueMapping(x, inMin, inMax, outMin, outMax) {
  return (x - inMin) * (outMax - outMin) / (inMax - inMin) + outMin;
}

const canvas = {
  width: 0,
  height: 0,
  init() {
    this.ele = document.createElement('canvas');
    $('.canvas-area').appendChild(this.ele);
    this.resize();
    window.addEventListener('resize', () => this.resize(), false);
    this.ctx = this.ele.getContext('2d');
    return this.ctx;
  },
  onResize(callback) {
    this.resizeCallback = callback;
  },
  resize() {
    this.width = this.ele.width = this.ele.offsetWidth;
    this.height = this.ele.height = this.ele.offsetHeight;
    this.resizeCallback && this.resizeCallback();
  },
  run(callback) {
    requestAnimationFrame(() => this.run(callback));
    callback(this.ctx);
  }
};

canvas.init();

const gradients = [
  ['#6e45e2', '#88d3ce'],
  ['#de6262', '#ffb88c'],
  ['#64b3f4', '#c2e59c'],
  ['#0fd850', '#f9f047'],
  ['#007adf', '#00ecbc'],
  ['#B6CEE8', '#F578DC'],
  ['#9be15d', '#00e3ae']
];

let waves = [];

const init = () => {
  waves = [];
  for (let i = 0; i < 5; i++) {
    const [start, stop] = gradients[Math.floor(Math.random() * gradients.length)];
    waves.push(new Wave(canvas, {
      start,
      stop,
      lineWidth: 1,
      xSpeed: valueMapping(Math.random(), 0, 1, -0.05, -0.08),
      amplitude: valueMapping(Math.random(), 0, 1, 0.05, 0.5),
      offset: Math.random() * 100
    }));
  }
};

document.addEventListener('click', () => {
  init();
});

init();

canvas.run(ctx => {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  waves.forEach(wave => {
    wave.draw(ctx);
  });
});

canvas.onResize(() => {
  init();
});